package cn.gjxblog.interceptor;

import cn.gjxblog.common.utils.JwtHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashSet;
import java.util.Set;

/**
 * @author gjx
 * @version v1.0
 * @Description
 * @date 2018/12/11 16:32
 */
@Slf4j
//@Component
public class HttpBasicAuthorizeInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {


        log.info("当前请求的路径为{}",httpServletRequest.getRequestURI());

        /**
         * 放行路径
         */
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        Set<String> urls = new HashSet<>();
        urls.add("/user/auth");
        urls.add("/user/get");
        urls.add("/user/add");
        urls.add("/user/getByEmail");
        urls.add("/user/enable");
        urls.add("/user/getById");
        for (String url : urls) {
            if(antPathMatcher.match(url,httpServletRequest.getRequestURI())){
                return true;
            }
        }

        String auth  = httpServletRequest.getHeader("Authorization");
        if(StringUtils.isEmpty(auth)){
            log.error("Authorization 不能为空");
            throw new RuntimeException("Authorization 不能为空");
        }
        try {
            JwtHelper.verifyToken(auth);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("认证失败");
            throw new RuntimeException("认证失败");
        }

    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
